from drf_spectacular.extensions import OpenApiViewExtension
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample
from drf_spectacular.types import OpenApiTypes


class GoodsViewSetOpenApi(OpenApiViewExtension):
    target_class = 'goods_app.views.GoodsViewSet'

    def view_replacement(self):
        from rest_framework.decorators import action
        from .serializers import (
            GoodsSerializer, GoodsCreateSerializer, GoodsListSerializer, 
            GoodsImageSerializer, GoodsImageCreateSerializer, GoodsUpdateSerializer
        )

        class Extended(self.target_class):
            @extend_schema(
                summary="创建货源",
                description="""
创建一个新的货源信息。

权限说明：
- 只有通过货主身份认证的用户可以创建货源

业务逻辑：
- 创建的货源默认状态为"待接单"
- 创建成功后返回包含ID的完整货源信息
- 货源自动归属于创建者
""",
                request=GoodsCreateSerializer,
                responses={201: GoodsSerializer},
                tags=["Goods"],
                examples=[
                    OpenApiExample(
                        '创建货源请求示例',
                        summary='创建货源请求示例',
                        description='创建货源的请求参数示例',
                        value={
                            "title": "沥青运输",
                            "description": "运输100吨沥青从广州到深圳",
                            "weight": "100.00",
                            "volume": "120.00",
                            "goods_type": "沥青",
                            "from_location": "广东省广州市天河区",
                            "from_longitude": "113.280661",
                            "from_latitude": "23.125178",
                            "to_location": "广东省深圳市南山区",
                            "to_longitude": "113.941944",
                            "to_latitude": "22.542500",
                            "loading_time": "2025-10-25T08:00:00Z",
                            "expected_arrival_time": "2025-10-25T18:00:00Z",
                            "expected_price": "1200.00"
                        }
                    ),
                    OpenApiExample(
                        '创建货源响应示例',
                        summary='创建货源响应示例',
                        description='创建货源成功的响应示例',
                        value={
                            "id": 1,
                            "user": {
                                "id": 1,
                                "phone": "13800138000",
                                "role": "shipper",
                                "avatar": "https://example.com/avatar.jpg",
                                "company": "ABC物流公司",
                                "credit_score": "4.8",
                                "date_joined": "2024-01-01T10:00:00Z",
                                "last_login": "2024-01-15T14:30:00Z"
                            },
                            "title": "沥青运输",
                            "description": "运输100吨沥青从广州到深圳",
                            "weight": "100.00",
                            "volume": "120.00",
                            "goods_type": "沥青",
                            "from_location": "广东省广州市天河区",
                            "from_longitude": "113.280661",
                            "from_latitude": "23.125178",
                            "to_location": "广东省深圳市南山区",
                            "to_longitude": "113.941944",
                            "to_latitude": "22.542500",
                            "loading_time": "2025-10-25T08:00:00Z",
                            "expected_arrival_time": "2025-10-25T18:00:00Z",
                            "expected_price": "1200.00",
                            "status": "pending",
                            "status_display": "待接单",
                            "images": [],
                            "created_at": "2025-10-20T10:00:00Z",
                            "updated_at": "2025-10-20T10:00:00Z"
                        },
                        status_codes=['201']
                    )
                ]
            )
            def create(self):
                pass

            @extend_schema(
                summary="更新货源",
                description="""
更新指定的货源信息。

权限说明：
- 只有通过货主身份认证且是货主本人才能更新货源信息
- 不能更新货源状态

业务逻辑：
- 只能更新自己发布的货源
- 货源状态只能通过专门的接口（如取消货源）进行修改
""",
                request=GoodsUpdateSerializer,
                responses={200: GoodsSerializer},
                tags=["Goods"],
                examples=[
                    OpenApiExample(
                        '更新货源请求示例',
                        summary='更新货源请求示例',
                        description='更新货源的请求参数示例',
                        value={
                            "title": "沥青运输",
                            "description": "运输100吨沥青从广州到深圳南山",
                            "weight": "100.00",
                            "volume": "120.00",
                            "goods_type": "沥青",
                            "from_location": "广东省广州市天河区",
                            "from_longitude": "113.280661",
                            "from_latitude": "23.125178",
                            "to_location": "广东省深圳市南山区科技园",
                            "to_longitude": "113.941944",
                            "to_latitude": "22.542500",
                            "loading_time": "2025-10-26T08:00:00Z",
                            "expected_arrival_time": "2025-10-26T18:00:00Z",
                            "expected_price": "1300.00"
                        }
                    ),
                    OpenApiExample(
                        '更新货源响应示例',
                        summary='更新货源响应示例',
                        description='更新货源成功的响应示例',
                        value={
                            "id": 1,
                            "user": {
                                "id": 1,
                                "phone": "13800138000",
                                "role": "shipper",
                                "avatar": "https://example.com/avatar.jpg",
                                "company": "ABC物流公司",
                                "credit_score": "4.8",
                                "date_joined": "2024-01-01T10:00:00Z",
                                "last_login": "2024-01-15T14:30:00Z"
                            },
                            "title": "沥青运输",
                            "description": "运输100吨沥青从广州到深圳南山",
                            "weight": "100.00",
                            "volume": "120.00",
                            "goods_type": "沥青",
                            "from_location": "广东省广州市天河区",
                            "from_longitude": "113.280661",
                            "from_latitude": "23.125178",
                            "to_location": "广东省深圳市南山区科技园",
                            "to_longitude": "113.941944",
                            "to_latitude": "22.542500",
                            "loading_time": "2025-10-26T08:00:00Z",
                            "expected_arrival_time": "2025-10-26T18:00:00Z",
                            "expected_price": "1300.00",
                            "status": "pending",
                            "status_display": "待接单",
                            "images": [],
                            "created_at": "2025-10-20T10:00:00Z",
                            "updated_at": "2025-10-22T10:00:00Z"
                        },
                        status_codes=['200']
                    )
                ]
            )
            @action(detail=True, methods=['post'])
            def update_goods(self):
                pass

            @extend_schema(
                summary="获取货源列表",
                description="""
获取当前货主用户创建的所有货源信息列表，作为暂存区使用。

权限说明：
- 只有经过认证的用户可以访问此接口
- 仅返回当前用户创建的货源

业务逻辑：
- 作为货主的个人暂存区，仅对货主本人可见
- 未发布的货源仅在此处可见
- 发布后的货源应通过Orders模块进行运单查询
- 支持按货物类型、状态等条件筛选
- 支持关键词搜索
- 支持按不同字段排序
""",
                responses={200: GoodsListSerializer(many=True)},
                parameters=[
                    OpenApiParameter(
                        name='status',
                        description='货源状态',
                        required=False,
                        type=str
                    ),
                    OpenApiParameter(
                        name='goods_type',
                        description='货物类型',
                        required=False,
                        type=str
                    ),
                    OpenApiParameter(
                        name='search',
                        description='搜索关键词，支持在标题、描述、装货地点、卸货地点中搜索',
                        required=False,
                        type=str
                    ),
                    OpenApiParameter(
                        name='ordering',
                        description='指定排序字段，支持的字段包括：created_at、loading_time、expected_price、weight。在字段名前加"-"表示降序排序，如"-created_at"表示按创建时间降序排序',
                        required=False,
                        type=str
                    ),
                ],
                tags=["Goods"],
                examples=[
                    OpenApiExample(
                        '货源列表响应示例',
                        summary='货源列表响应示例',
                        description='返回当前用户创建的货源列表示例数据',
                        value=[
                            {
                                "id": 1,
                                "user_name": "13800138000",
                                "title": "沥青运输",
                                "weight": "100.00",
                                "from_location": "广东省广州市天河区",
                                "to_location": "广东省深圳市南山区",
                                "loading_time": "2025-10-25T08:00:00Z",
                                "expected_price": "1200.00",
                                "status": "pending",
                                "status_display": "待接单",
                                "created_at": "2025-10-20T10:00:00Z"
                            },
                            {
                                "id": 2,
                                "user_name": "13800138000",
                                "title": "沥青运输",
                                "weight": "50.00",
                                "from_location": "广东省东莞市",
                                "to_location": "广东省佛山市",
                                "loading_time": "2025-10-26T09:00:00Z",
                                "expected_price": "800.00",
                                "status": "draft",
                                "status_display": "草稿",
                                "created_at": "2025-10-21T10:00:00Z"
                            }
                        ],
                        status_codes=['200']
                    )
                ]
            )
            def list(self):
                pass

            @extend_schema(
                summary="获取货源详情",
                description="""
根据ID获取特定货源的详细信息。

权限说明：
- 只有经过认证的用户可以访问此接口
- 仅能访问自己创建的货源

特殊说明：
- 当ID为'me'时，返回当前用户发布的所有货源
""",
                responses={200: GoodsSerializer},
                parameters=[
                    OpenApiParameter(
                        name='id',
                        description='货源ID或"me"（表示当前用户的所有货源）',
                        required=True,
                        type=str,
                        location=OpenApiParameter.PATH
                    )
                ],
                tags=["Goods"],
                examples=[
                    OpenApiExample(
                        '货源详情响应示例',
                        summary='货源详情响应示例',
                        description='返回货源详细信息的示例数据',
                        value={
                            "id": 1,
                            "user": {
                                "id": 1,
                                "phone": "13800138000",
                                "role": "shipper",
                                "avatar": "https://example.com/avatar.jpg",
                                "company": "ABC物流公司",
                                "credit_score": "4.8",
                                "date_joined": "2024-01-01T10:00:00Z",
                                "last_login": "2024-01-15T14:30:00Z"
                            },
                            "title": "沥青运输",
                            "description": "运输100吨沥青从广州到深圳",
                            "weight": "100.00",
                            "volume": "120.00",
                            "goods_type": "沥青",
                            "from_location": "广东省广州市天河区",
                            "from_longitude": "113.280661",
                            "from_latitude": "23.125178",
                            "to_location": "广东省深圳市南山区",
                            "to_longitude": "113.941944",
                            "to_latitude": "22.542500",
                            "loading_time": "2025-10-25T08:00:00Z",
                            "expected_arrival_time": "2025-10-25T18:00:00Z",
                            "expected_price": "1200.00",
                            "status": "pending",
                            "status_display": "待接单",
                            "images": [
                                {
                                    "id": 1,
                                    "image_url": "https://example.com/goods_image1.jpg",
                                    "description": "货物照片",
                                    "created_at": "2025-10-20T10:30:00Z"
                                }
                            ],
                            "created_at": "2025-10-20T10:00:00Z",
                            "updated_at": "2025-10-20T10:00:00Z"
                        },
                        status_codes=['200']
                    )
                ]
            )
            def retrieve(self):
                pass

            @extend_schema(
                summary="删除货源",
                description="""
删除指定的货源信息。

权限说明：
- 只有通过货主身份认证且是货主本人才能删除货源信息

业务逻辑：
- 只能删除自己发布的货源
""",
                responses={
                    200: OpenApiTypes.OBJECT,
                    403: OpenApiTypes.OBJECT,
                    404: OpenApiTypes.OBJECT
                },
                parameters=[
                    OpenApiParameter(
                        name='id',
                        description='货源ID（不能使用"me"参数）',
                        required=True,
                        type=str,
                        location=OpenApiParameter.PATH
                    )
                ],
                tags=["Goods"],
                examples=[
                    OpenApiExample(
                        '删除货源请求示例',
                        summary='删除货源请求示例',
                        description='删除货源的请求参数示例（无需参数）',
                        value={},
                        request_only=True
                    ),
                    OpenApiExample(
                        '删除货源响应示例',
                        summary='删除货源响应示例',
                        description='删除货源成功的响应示例',
                        value={
                            "message": "货源删除成功"
                        },
                        status_codes=['200']
                    ),
                    OpenApiExample(
                        '权限不足错误',
                        summary='权限不足错误',
                        description='权限不足的错误响应示例',
                        value={
                            "error": "只有货源的所有者才能删除货源"
                        },
                        status_codes=['403']
                    )
                ]
            )
            @action(detail=True, methods=['post'])
            def delete_goods(self):
                pass

        return Extended